<template>
  <div>
    <vxe-card title="" class="w-full" :border="false">
      <AuForm
        ref="formRef"
        :formList="formList"
        labelWidth="100px"
        @submit="onsubmit"
      />
    </vxe-card>

    <vxe-card
      title=""
      class="w-full mt-[16px] h-[36vh]"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <div class="flex items-center">
          <span class="text-[--autata-font-color]"
            >{{ t(TREND_TITLE_G) }} ({{ matUnit }})</span
          >

          <el-radio-group
            v-model="tabActive"
            class="ml-2"
            @change="changeRadio"
          >
            <el-radio-button
              :label="t('tea_infuser.dashboard.cabinet.total_trend')"
              value="1"
            />
            <el-radio-button
              :label="t('tea_infuser.dashboard.cabinet.use_amount_trend')"
              value="2"
            />
            <el-radio-button
              :label="t('tea_infuser.dashboard.cabinet.supply_amount_trend')"
              value="3"
            />
          </el-radio-group>
        </div>
        <el-link
          type="primary"
          :underline="false"
          @click="exportExcelGroup('mat')"
          >{{ t("table.export") }}
        </el-link>
      </h3>
      <div
        ref="matLineChartRef"
        v-loading="matChartLoading"
        style="width: 99%; height: calc(36vh - 56px)"
      />
    </vxe-card>

    <vxe-card
      title=""
      class="w-full mt-[16px] h-[46vh]"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <span class="text-[--autata-font-color]"
          >{{ t(MATERIAL_TOP_5) }} ({{ matTopUnit }})
        </span>
      </h3>
      <div v-loading="matTopBarLoading" class="flex">
        <div
          ref="matTopBarChartRef"
          style="width: 60%; height: calc(46vh - 56px)"
        />
        <div
          ref="matPieChartRef"
          style="width: 39%; height: calc(46vh - 56px)"
        />
      </div>
    </vxe-card>

    <vxe-card
      title=""
      class="mt-[16px] h-[48vh] w-full pb-4"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <span class="text-[--autata-font-color]">{{
          t(MATERIAL_TABLE_TITLE)
        }}</span>
        <el-link
          type="primary"
          :underline="false"
          @click="exportExcelGroup('mat')"
          >{{ t("table.export") }}
        </el-link>
      </h3>
      <div class="h-[calc(100%_-_45px)]">
        <AuTable v-if="active === 2" ref="tableMatRef" v-bind="gridOptionMat" />
      </div>
    </vxe-card>

    <!--    生产数据趋势分析   -->
    <vxe-card
      title=""
      class="w-full mt-[16px] h-[36vh]"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <div class="flex items-center">
          <span class="text-[--autata-font-color]">{{ t(TREND_TITLE_B) }}</span>

          <el-radio-group
            v-model="tabProdActive"
            class="ml-2"
            @change="changeProdRadio"
          >
            <el-radio-button
              :label="t('tea_infuser.dashboard.cabinet.total_trend')"
              value="1"
            />
            <el-radio-button
              :label="t('tea_infuser.dashboard.cabinet.normal_amount_trend')"
              value="2"
            />
            <el-radio-button
              :label="t('tea_infuser.dashboard.cabinet.cancel_amount_trend')"
              value="3"
            />
          </el-radio-group>
        </div>

        <el-link
          type="primary"
          :underline="false"
          @click="exportExcelGroup('prod')"
          >{{ t("table.export") }}
        </el-link>
      </h3>
      <div
        ref="prodLineChartRef"
        v-loading="prodChartLoading"
        style="width: 99%; height: calc(36vh - 56px)"
      />
    </vxe-card>

    <vxe-card
      title=""
      class="mt-[16px] h-[46vh] w-full"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <span class="text-[--autata-font-color]">{{ t(PROD_TOP_5) }}</span>
      </h3>
      <div v-loading="prodTopBarLoading" class="flex">
        <div
          ref="prodTopBarChartRef"
          style="width: 60%; height: calc(46vh - 56px)"
        />
        <div
          ref="prodPieChartRef"
          style="width: 39%; height: calc(46vh - 56px)"
        />
      </div>
    </vxe-card>

    <vxe-card
      title=""
      class="mt-[16px] h-[48vh] w-full pb-4"
      :border="false"
      :padding="false"
    >
      <h3 class="m-[20px] mb-0 flex items-center justify-between">
        <span class="text-[--autata-font-color]">{{
          t(PROD_TABLE_TITLE)
        }}</span>
        <el-link
          type="primary"
          :underline="false"
          @click="exportExcelGroup('prod')"
          >{{ t("table.export") }}
        </el-link>
      </h3>
      <div class="h-[calc(100%_-_45px)]">
        <AuTable
          v-if="active === 2"
          ref="tableProdRef"
          v-bind="gridOptionProd"
        />
      </div>
    </vxe-card>
  </div>
</template>

<script setup lang="ts">
import { AuForm } from "@/components/AuForm";
import { computed, onMounted, reactive, ref, watch } from "vue";
import dayjs from "dayjs";
import { storeGroupSelect } from "@/utils/formSelect";
import { deviceGetList } from "@/api/teaInfuser/device";
import { getStoreList } from "@/api/teaInfuser/store";
import { getMaterialList } from "@/api/cabinet/material";
import {
  PROD_TABLE_TITLE,
  gridOptionBase,
  MATERIAL_TABLE_TITLE,
  MATERIAL_TOP_5,
  PROD_TOP_5,
  TREND_TITLE_B,
  TREND_TITLE_G
} from "@/views/teaInfuser/dashboard/analysis/constant";
import { useDark, useECharts } from "@pureadmin/utils";
import { cloneDeep } from "lodash-unified";
import {
  getFormulaCharts,
  getFormulaTopCharts,
  getMaterialCharts,
  getMaterialTopCharts
} from "@/api/cabinet/analysis";
import { MeasuringUnit, MeasuringWeight } from "@/utils/tool";
import {
  COLOR_LIST,
  DEVICE_TYPE_ENUM,
  LINE_COLOR,
  TEXT_COLOR,
  THEME_COLOR
} from "@/utils/constants";
import { AuTable } from "@/components/AuTable";
import { PropDefines } from "@/components/AuTable/type";
import exportExcel from "@/utils/exportExcel";
import { useI18n } from "vue-i18n";
import { pickerOptions } from "./tools";

const emit = defineEmits(["confirm"]);
const props = defineProps<{
  active: number;
}>();
const { t, locale } = useI18n();
// const props = defineProps({});
const { isDark } = useDark();
const materialList = ref([]);
const matUnit = ref("g");
const matTopUnit = ref("g");
const theme = computed(() => (isDark.value ? "dark" : "light"));

const formRef = ref();
const formList = ref([
  {
    type: "el-date-picker",
    key: "scsj",
    inType: "datetimerange",
    label: "tea_infuser.dashboard.cabinet.production_time",
    span: 12,
    rangeSeparator: "至",
    startPlaceholder: "tea_infuser.dashboard.cabinet.start_time",
    endPlaceholder: "tea_infuser.dashboard.cabinet.end_time",
    valueFormat: "YYYY-MM-DD HH:mm:ss",
    ...pickerOptions(formRef),
    defaultValue: [
      dayjs().subtract(10, "day").format("YYYY-MM-DD HH:mm:ss"),
      dayjs().format("YYYY-MM-DD HH:mm:ss")
    ]
  },
  () => storeGroupSelect("group_idlist", {}, true),
  {
    type: "select",
    key: "store_id",
    label: "tea_infuser.dashboard.cabinet.store_name",
    placeholder: "tea_infuser.dashboard.cabinet.store_name_placeholder",
    valueKey: "id",
    labelKey: "name",
    filterable: true,
    options: []
  },
  {
    type: "select",
    key: "device_id",
    label: "tea_infuser.dashboard.cabinet.device_code",
    placeholder: "tea_infuser.dashboard.cabinet.device_code_placeholder",
    valueKey: "device_id",
    labelKey: "device_id",
    filterable: true,
    options: [],
    popperClass: "device-popper"
  },
  {
    type: "select",
    key: "material_id",
    label: "tea_infuser.dashboard.cabinet.material_name",
    placeholder: "tea_infuser.dashboard.cabinet.material_name_placeholder",
    valueKey: "material_id",
    labelKey: "name",
    filterable: true,
    options: [],
    popperClass: "device-popper"
  }
]);

const tabActive = ref("1");
const matChartLoading = ref(false);
const matLineChartRef = ref();
const { setOptions: setMatLineOptions } = useECharts(matLineChartRef, {
  theme
});

const matTopBarLoading = ref(false);
const matTopBarChartRef = ref();
const { setOptions: setMatBarOptions } = useECharts(matTopBarChartRef, {
  theme
});
const matPieChartRef = ref();
const { setOptions: setMatPieOptions } = useECharts(matPieChartRef, {
  theme
});

const gridOptionMat = reactive<PropDefines>({
  ...cloneDeep(gridOptionBase),
  columns: [
    {
      field: "time",
      title: "tea_infuser.dashboard.production_date",
      width: 170,
      align: "center"
    },
    {
      field: "usage_num",
      title: "tea_infuser.dashboard.material_usage",
      minWidth: 150,
      align: "center"
    },
    {
      field: "repair_num",
      title: "tea_infuser.dashboard.repair_amount",
      minWidth: 150,
      align: "center"
    },
    {
      field: "discard_num",
      title: "tea_infuser.dashboard.scrap_amount",
      minWidth: 150,
      align: "center"
    }
  ]
});

const prodChartLoading = ref(false);
const tabProdActive = ref("1");
const prodLineChartRef = ref();
const { setOptions: setProdLineOptions } = useECharts(prodLineChartRef, {
  theme
});

const prodTopBarLoading = ref(false);
const prodTopBarChartRef = ref();
const { setOptions: setProdBarOptions } = useECharts(prodTopBarChartRef, {
  theme
});
const prodPieChartRef = ref();
const { setOptions: setProdPieOptions } = useECharts(prodPieChartRef, {
  theme
});

const gridOptionProd = reactive<PropDefines>({
  ...cloneDeep(gridOptionBase),
  columns: [
    {
      field: "time",
      title: "tea_infuser.dashboard.tea_powder.production_date",
      width: 170,
      align: "center"
    },
    {
      field: "store_num",
      title: "tea_infuser.dashboard.tea_powder.store",
      minWidth: 150,
      align: "center"
    },
    {
      field: "normal_num",
      title: "tea_infuser.dashboard.tea_powder.normal_amount",
      minWidth: 150,
      align: "center"
    },
    {
      field: "unusual_num",
      title: "tea_infuser.dashboard.tea_powder.abnormal_amount",
      minWidth: 150,
      align: "center"
    },
    {
      field: "cancle_num",
      title: "tea_infuser.dashboard.tea_powder.cancel_amount",
      minWidth: 150,
      align: "center"
    }
  ]
});

const exportExcelGroup = (type: string) => {
  if (type === "mat") {
    exportExcel(
      gridOptionMat.columns.map(v => {
        return {
          ...v,
          title: t(v.title)
        };
      }),
      gridOptionMat.dataSource,
      tabActive.value === "1"
        ? t(MATERIAL_TABLE_TITLE)
        : t(MATERIAL_TABLE_TITLE)
    );
  } else if (type === "prod") {
    exportExcel(
      gridOptionProd.columns.map(v => {
        return {
          ...v,
          title: t(v.title)
        };
      }),
      gridOptionProd.dataSource,
      tabProdActive.value === "1" ? t(PROD_TABLE_TITLE) : t(PROD_TABLE_TITLE)
    );
  }
};

const getSearchData = () => {
  const param = cloneDeep(formRef.value.getFormData());

  const groupObjArr = [];
  if (param.group_idlist != undefined && param.group_idlist.length > 0) {
    for (const item of param.group_idlist) {
      groupObjArr.push({ group_id: item });
    }
    param["group_idlist"] = JSON.stringify(groupObjArr);
  }

  param["create_start_time"] = param.scsj[0];
  param["create_end_time"] = param.scsj[1];
  param.size = 0;
  param.start_page = 0;
  param.device_type = DEVICE_TYPE_ENUM.CABINET;
  param.hiddenDeviceType = true;

  delete param["scsj"];
  return param;
};

// region  物料数据趋势图

/**
 * 获取状态
 */
const getStatus = () => {
  let param;
  if (tabActive.value === "1") {
    // 汇总
    param = {
      groupname: "status"
    };
  } else if (tabActive.value === "2") {
    // 用料
    const statusArray = [
      { status: 1 },
      { status: 2 },
      { status: 4 },
      { status: 5 },
      { status: 6 }
    ];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  } else if (tabActive.value === "3") {
    // 补料
    const statusArray = [{ status: 3 }];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  } else if (tabActive.value === "4") {
    // 报废
    const statusArray = [{ status: 2 }, { status: 5 }, { status: 6 }];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  } else if (tabActive.value === "5") {
    // 校准
    const statusArray = [{ status: 4 }];
    param = {
      groupname: "material_id",
      status: JSON.stringify(statusArray)
    };
  }

  return param;
};

/**
 * 获取最大值和单位
 * @param list
 */
const getMaxAndUnit = (
  list: any[]
): {
  maxNum: number;
  weightUnit: "g" | "kg" | "ton";
  weightText: string;
} => {
  //得出最大值
  const liveDataNum = [];
  list.forEach((item, i) => {
    if (!isNaN(item.normal_num)) {
      liveDataNum.push(item.normal_num);
    }
    if (!isNaN(item.waste_num)) {
      liveDataNum.push(item.waste_num);
    }
    if (!isNaN(item.calibration_num)) {
      liveDataNum.push(item.calibration_num);
    }
    if (!isNaN(item.cancle_num)) {
      liveDataNum.push(item.cancle_num);
    }
    if (!isNaN(item.unusual_num)) {
      liveDataNum.push(item.unusual_num);
    }
    if (!isNaN(item.repair_num)) {
      liveDataNum.push(item.repair_num);
    }
    if (!isNaN(item.num)) {
      liveDataNum.push(item.num);
    }
  });
  let maxNum = 0;
  if (liveDataNum.length > 0) {
    maxNum = liveDataNum.reduce((max, current) => {
      return Math.max(max, current);
    });
  }
  let weightUnit: "g" | "kg" | "ton" = "ton";
  let weightText = "";
  //根据最大值得出换算的单位
  if (maxNum >= 1000000) {
    weightUnit = "ton";
    weightText = "吨";
  } else if (maxNum >= 1000) {
    weightUnit = "kg";
    weightText = "kg";
  } else {
    weightUnit = "g";
    weightText = "g";
  }

  return {
    maxNum,
    weightUnit,
    weightText
  };
};

/**
 * 设置折线图数据
 * @param xArr
 * @param allArr
 */
const setLineOptionData = (
  xArr: string[],
  allArr: { [key: string]: any[] }
) => {
  const series = [];
  let index = 0;
  for (const allArrKey in allArr) {
    series.push({
      data: allArr[allArrKey],
      type: "line",
      name: t(allArrKey),
      showSymbol: false,
      lineStyle: {
        color: COLOR_LIST[index]
      }
    });
    index++;
  }

  setMatLineOptions({
    title: {
      show: false
    },
    grid: {
      left: "2%",
      right: "2%",
      bottom: "6%",
      top: "6%",
      containLabel: true
    },
    color: COLOR_LIST,
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "cross"
      },
      appendToBody: true, // 提示框浮在页面上，不受图表区域限制
      position: function (point, params, dom, rect, size) {
        // 自定义定位逻辑
        return [point[0], point[1]];
      }
    },
    xAxis: {
      type: "category",
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    series
  });
};

const setAllData = (
  list: any[],
  xArr: string[],
  weightUnit: "g" | "kg" | "ton"
) => {
  gridOptionMat.columns = [
    {
      field: "time",
      title: "tea_infuser.dashboard.production_date",
      width: 170,
      align: "center"
    },
    {
      field: "usage_num",
      // title: `${t("tea_infuser.dashboard.material_usage")}(${weightUnit})`,
      title: `tea_infuser.dashboard.material_usage`,
      minWidth: 150,
      align: "center"
    },
    {
      field: "repair_num",
      // title: `${t("tea_infuser.dashboard.repair_amount")}(${weightUnit})`,
      title: `tea_infuser.dashboard.repair_amount`,
      minWidth: 150,
      align: "center"
    },
    {
      field: "discard_num",
      title: `tea_infuser.dashboard.scrap_amount`,
      minWidth: 150,
      align: "center"
    },
    {
      field: `calibration_num`,
      title: `tea_infuser.dashboard.calibration_amount`,
      minWidth: 150,
      align: "center"
    }
  ];
  gridOptionMat.dataSource = list.map(item => {
    return {
      time: item.time,
      usage_num: MeasuringUnit(
        2,
        item.normal_num +
          item.waste_num +
          item.calibration_num +
          item.cancle_num +
          item.unusual_num
      ),
      repair_num: MeasuringUnit(2, item.repair_num),
      discard_num: MeasuringUnit(
        2,
        item.waste_num + item.cancle_num + item.unusual_num
      ),
      calibration_num: MeasuringUnit(2, item.calibration_num),
      num: MeasuringUnit(2, item.num)
    };
  });
  // 用料
  const useArr = list.map(item => {
    const num =
      item.normal_num +
      item.waste_num +
      item.calibration_num +
      item.cancle_num +
      item.unusual_num;

    return Number(MeasuringWeight(weightUnit, num));
  });
  // 补料
  const repairArr = list.map(item =>
    Number(MeasuringWeight(weightUnit, item.repair_num))
  );
  // // 报废
  // const scrapArr = list.map(item =>
  //   Number(MeasuringWeight(weightUnit, item.cancle_num + item.unusual_num))
  // );
  // // 校准
  // const calibrationArr = list.map(item =>
  //   Number(MeasuringWeight(weightUnit, item.calibration_num))
  // );

  setLineOptionData(xArr, {
    "tea_infuser.dashboard.usage": useArr,
    "tea_infuser.dashboard.repair": repairArr
  });
};

const setMaterialData = (
  list: any[],
  xArr: string[],
  weightUnit: "g" | "kg" | "ton"
) => {
  const dataObj: { [key: string]: any[] } = {};

  gridOptionMat.columns = [
    {
      field: "time",
      title: "tea_infuser.dashboard.production_date",
      width: 170,
      align: "center"
    },
    {
      field: "material_name",
      title: "tea_infuser.dashboard.material",
      minWidth: 150,
      align: "center"
    },
    {
      field: "num",
      // TODO: title: `${t("tea_infuser.dashboard.material_usage")}(${weightUnit})`,
      title: `tea_infuser.dashboard.material_usage`,
      minWidth: 150,
      align: "center"
    }
  ];
  gridOptionMat.dataSource = list.map(v => {
    return {
      ...v,
      num: MeasuringUnit(2, v.num)
    };
  });
  xArr = [...new Set(xArr)];
  for (let i = 0; i < xArr.length; i++) {
    const filter = list.filter(item => item.time === xArr[i]);
    for (const item of filter) {
      const key =
        materialList.value.find(v => v.material_id === item.material_id)
          ?.material_name ?? item.material_name;
      if (dataObj[key] === undefined) {
        dataObj[key] = [];
      }
      console.log(item);
      if (item.time === xArr[i]) {
        dataObj[key].push(MeasuringWeight(weightUnit, item.num));
      } else {
        dataObj[key].push(0);
      }
    }
  }

  for (const key in dataObj) {
    const isAllZero = dataObj[key]?.every(item => item === 0);
    if (isAllZero) {
      delete dataObj[key];
    }
  }

  console.log(dataObj);
  setLineOptionData(xArr, dataObj);
};

const getMatLineChart = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  const statusParam = getStatus();
  try {
    const res = await getMaterialCharts({ ...param, ...statusParam });
    console.log(res);
    const list = res.data.reverse();
    const xArr = list.map(item => item.time);
    const { weightUnit } = getMaxAndUnit(list);
    matUnit.value = weightUnit;

    if (tabActive.value === "1") {
      setAllData(list, xArr, weightUnit);
    } else {
      setMaterialData(list, xArr, weightUnit);
    }
  } catch (e) {}
};

const changeRadio = () => {
  getMatLineChart();
};

// endregion

// region 物料top5分布
const setTopOptionData = (xArr: string[], yArr: number[]) => {
  setMatBarOptions({
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "value",
      boundaryGap: [0, 0.01],
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    yAxis: {
      type: "category",
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    series: [
      {
        name: t("tea_infuser.dashboard.cabinet.total"),
        type: "bar",
        data: yArr.map((v, i) => ({
          value: v,
          itemStyle: {
            color: COLOR_LIST[i]
          }
        }))
      }
    ]
  });
};

const setTopPieOptionData = (data: any[]) => {
  setMatPieOptions({
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {d}%"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    series: [
      {
        name: t("tea_infuser.dashboard.cabinet.ranking_ratio"),
        type: "pie",
        radius: "70%",
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  });
};

const getMatTopCharts = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  const statusParam = getStatus();
  try {
    const res = await getMaterialTopCharts({ ...param, ...statusParam });
    console.log(res);
    const list = res.data;
    //得出最大值
    const liveDataNum = [];
    for (const v of list) {
      liveDataNum.push(v.num);
    }
    let maxNum = 0;
    if (liveDataNum.length > 0) {
      maxNum = liveDataNum.reduce((max, current) => {
        return Math.max(max, current);
      });
    }
    let weightUnit = "g";
    let weightText = "";
    //根据最大值得出换算的单位
    if (maxNum >= 1000000) {
      weightUnit = "ton";
      weightText = "吨";
    } else if (maxNum >= 1000) {
      weightUnit = "kg";
      weightText = "kg";
    } else {
      weightUnit = "g";
      weightText = "g";
    }
    matTopUnit.value = weightUnit;
    const xArr = list.map(
      item =>
        materialList.value.find(v => v.material_id === item.material_id)
          ?.material_name ?? item.material_name
    );
    const yArr = list
      .map(item => Number(MeasuringWeight(weightUnit as any, item.num)))
      .sort((a, b) => b - a);
    setTopOptionData(xArr, yArr);

    const pieData = list.map((v, i) => {
      return {
        value: v.num,
        name:
          materialList.value.find(h => h.material_id == v.material_id)
            ?.material_name ?? v.material_name,
        itemStyle: {
          color: COLOR_LIST[i]
        }
      };
    });
    setTopPieOptionData(pieData);
  } catch (e) {}
};
// endregion

// region 生产数据趋势图
const changeProdRadio = () => {
  getProdFormulaCharts();
};

const setProdLineOptionData = (series: any[], xArr: any[]) => {
  setProdLineOptions({
    title: {
      show: false
    },
    grid: {
      left: "2%",
      right: "2%",
      bottom: "6%",
      top: "6%",
      containLabel: true
    },
    color: COLOR_LIST,
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross"
      }
    },
    xAxis: {
      type: "category",
      axisTick: {
        show: false // 通过设置 show 为 false 来隐藏刻度线
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    yAxis: {
      type: "value",
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    series
  });
};

const getProdFormulaCharts = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  if (tabProdActive.value == "1") {
    param["groupname"] = "status";
  } else if (tabProdActive.value == "2") {
    param["status"] = "1";
    param["groupname"] += "formula_subid";
  } else if (tabProdActive.value == "3") {
    param["status"] += "2";
    param["groupname"] += "formula_subid";
  }
  param["device_type"] = "";

  const res = await getFormulaCharts(param);

  const list = res.data.reverse();
  const xArr = list.map(item => item.time);
  gridOptionProd.dataSource = list;
  if (tabProdActive.value === "1") {
    const series = [
      {
        name: t("tea_infuser.dashboard.cabinet.normal_amount"),
        type: "line",
        data: list.map(item => item.normal_num),
        showSymbol: false,
        lineStyle: {
          color: COLOR_LIST[0]
        }
      },
      {
        name: t("tea_infuser.dashboard.cabinet.cancel_amount"),
        type: "line",
        data: list.map(item => item.cancle_num),
        showSymbol: false,
        lineStyle: {
          color: COLOR_LIST[1]
        }
      }
      // {
      //   name: "异常",
      //   type: "line",
      //   data: list.map(item => item.abnormal_num),
      //   showSymbol: false,
      //   areaStyle: {}
      // }
    ];

    gridOptionProd.columns = [
      {
        field: "time",
        title: "tea_infuser.dashboard.tea_powder.production_date",
        width: 170,
        align: "center"
      },
      {
        field: "normal_num",
        title: "tea_infuser.dashboard.tea_powder.normal_amount",
        minWidth: 150,
        align: "center"
      },
      {
        field: "unusual_num",
        title: "tea_infuser.dashboard.tea_powder.abnormal_amount",
        minWidth: 150,
        align: "center"
      },
      {
        field: "cancle_num",
        title: "tea_infuser.dashboard.tea_powder.cancel_amount",
        minWidth: 150,
        align: "center"
      }
    ];

    setProdLineOptionData(series, xArr);
  } else {
    gridOptionProd.columns = [
      {
        field: "time",
        title: "tea_infuser.dashboard.tea_powder.production_date",
        width: 170,
        align: "center"
      },
      {
        field: "formula_name",
        title: "tea_infuser.dashboard.tea_powder.product",
        minWidth: 150,
        align: "center"
      },
      {
        field: "num",
        title: "tea_infuser.dashboard.tea_powder.output",
        minWidth: 150,
        align: "center"
      }
    ];
    const series = [
      {
        name:
          tabProdActive.value === "2"
            ? t("tea_infuser.dashboard.cabinet.normal_amount")
            : t("tea_infuser.dashboard.cabinet.cancel_amount"),
        type: "line",
        data: list.map(item => item.num),
        showSymbol: false,
        lineStyle: {
          color: COLOR_LIST[0]
        }
      }
    ];
    setProdLineOptionData(series, xArr);
  }
};
// endregion

// region 物料top5分布
const setProdTopOptionData = (xArr: string[], yArr: string[]) => {
  setProdBarOptions({
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    dataZoom: [
      {
        type: "inside",
        yAxisIndex: 0,
        realtime: true, //实时更新
        width: 20,
        right: 10,
        start: (function () {
          // 如果数据少于5条，不需要滚动条
          const dataLength = yArr.length;
          if (dataLength <= 7) {
            return 0; // 显示全部
          } else {
            // 固定显示5条数据
            return 100 - Math.round((7 / dataLength) * 100);
          }
        })(),
        end: 100,
        zoomOnMouseWheel: false, // 启用鼠标滚轮缩放
        moveOnMouseWheel: true // 启用鼠标滚轮平移
      }
      // {
      //   type: "inside",
      //   yAxisIndex: 0,
      //   start: 0,
      //   end: 100,
      //   zoomLock: false,
      //   zoomOnMouseWheel: false, // 启用鼠标滚轮缩放
      //   moveOnMouseWheel: true // 启用鼠标滚轮平移
      //   // preventDefaultMouseWheel: true // 阻止浏览器默认滚动行为
      // }
    ],
    xAxis: {
      type: "value",
      boundaryGap: [0, 0.01],
      splitLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      }
    },
    yAxis: {
      type: "category",
      axisTick: {
        show: false // 通过设置 show 为 false 来隐藏刻度线
      },
      axisLine: {
        lineStyle: {
          color: LINE_COLOR
        }
      },
      axisLabel: {
        color: TEXT_COLOR
      },
      data: xArr
    },
    series: [
      {
        name: t("tea_infuser.dashboard.cabinet.total"),
        type: "bar",
        data: yArr.map((v, i) => ({
          value: v,
          itemStyle: {
            color: COLOR_LIST[i]
          }
        }))
      }
    ]
  });
};

const setProdTopPieOptionData = (data: any[]) => {
  setProdPieOptions({
    tooltip: {
      trigger: "item"
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true
    },
    series: [
      {
        name: t("tea_infuser.dashboard.cabinet.ranking_ratio"),
        type: "pie",
        radius: "70%",
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  });
};

const getProdTopCharts = async () => {
  const param = getSearchData();
  param["grouptime"] = "day";
  param["device_type"] = "";
  try {
    const res = await getFormulaTopCharts({ ...param });
    console.log(res);
    const list = res.data;
    const xArr = list.map(item => item.formula_name);
    const yArr = list.map(item => item.num).sort((a, b) => b - a);
    setProdTopOptionData(xArr, yArr);

    const pieData = list.map((v, i) => {
      return {
        value: v.num,
        name: v.formula_name,
        itemStyle: {
          color: COLOR_LIST[i]
        }
      };
    });
    setProdTopPieOptionData(pieData);
  } catch (e) {}
};
// endregion

const init = () => {
  deviceGetList({
    size: 0
  }).then(res => {
    formRef.value.setFormProps("device_id", {
      options: res.data.filter(item => item.device_model.includes("ATT-G"))
    });
  });

  getStoreList({
    size: 0
  }).then(res => {
    formRef.value.setFormProps("store_id", {
      options: res.data
    });
  });

  getMaterialList({
    size: 0
  }).then(res => {
    materialList.value = res.data ?? [];
    formRef.value.setFormProps("material_id", {
      options: res.data
    });
  });

  onsubmit();
};

const onsubmit = () => {
  getMatLineChart();
  getMatTopCharts();
  getProdFormulaCharts();
  getProdTopCharts();
};

watch(() => locale.value, onsubmit);

onMounted(() => {
  init();
});
</script>
